package _02_链表;

import java.util.Arrays;

public class _725_分隔链表 {

    public ListNode[] splitListToParts(ListNode head, int k) {
        // 记录元素个数
        int[] ints = new int[k];
        // 分割链表集合
        ListNode[] nodes = new ListNode[k];
        // 初始化元素记录个数
        for (int i = 0; i < ints.length; i++) {
            ints[i] = i + 1;
        }
        // 遍历一遍，寻找链表元素个数
        int total = calculateListCount(head);
        if (k < total) {
            // 计算
            int consult = total / k;
            int remainder = total % k;
            ints[0] = consult + (remainder != 0? 1: 0);
            for (int i = 1; i < ints.length; i++) {
                ints[i] = ints[i - 1] + consult;
                if (i < remainder) {
                    ints[i]++;
                }
            }
        }
        int count = 0;
        int storeIndex = 0;
        // 遍历链表，分割链表
        ListNode node = head;
        while (node != null && count++ > 0) {
            ListNode next = node.next;
            if (count == ints[storeIndex]) {
                System.out.println(count);
                node.next = null;
                nodes[storeIndex++] = head;
                head = next;
            }
            node = next;
        }
        return nodes;
    }

    public int calculateListCount(ListNode head) {
        int count = 0;
        ListNode node = head;
        while (node != null) {
            count++;
            node = node.next;
        }
        return count;
    }

}
